<template>
  <div class="min-h-screen p-4">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6 flex justify-between items-center">
        <div>
          <h1 class="text-3xl font-bold text-gray-900 mb-2">我的预约</h1>
          <p class="text-gray-600">管理您创建的预约和收到的申请</p>
        </div>
        <button 
          @click="$router.push('/')"
          class="btn-secondary flex items-center"
        >
          <i class="fas fa-arrow-left mr-2"></i>
          返回首页
        </button>
      </div>

      <!-- 标签页切换 -->
      <div class="mb-6">
        <div class="border-b border-gray-200">
          <nav class="-mb-px flex space-x-8">
            <button
              @click="activeTab = 'appointments'"
              :class="[
                'py-2 px-1 border-b-2 font-medium text-sm',
                activeTab === 'appointments'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              ]"
            >
              我创建的预约 ({{ appointments.length }})
            </button>
            <button
              @click="activeTab = 'applications'"
              :class="[
                'py-2 px-1 border-b-2 font-medium text-sm',
                activeTab === 'applications'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
              ]"
            >
              申请审核 
              <span v-if="pendingCount > 0" class="ml-1 bg-red-500 text-white text-xs px-2 py-1 rounded-full">
                {{ pendingCount }}
              </span>
            </button>
          </nav>
        </div>
      </div>

      <!-- 我创建的预约 -->
      <div v-if="activeTab === 'appointments'" class="space-y-4">
        <div v-if="loading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <div v-else-if="appointments.length === 0" class="text-center py-12">
          <div class="text-gray-400 text-6xl mb-4">📅</div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">暂无预约</h3>
          <p class="text-gray-500 mb-4">您还没有创建任何预约</p>
          <router-link
            to="/create"
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
          >
            创建预约
          </router-link>
        </div>

        <div v-else class="grid gap-4">
          <div
            v-for="appointment in appointments"
            :key="appointment.id"
            class="glass rounded-lg p-6 hover:shadow-lg transition-shadow"
          >
            <div class="flex justify-between items-start mb-4">
              <div>
                <h3 class="text-xl font-semibold text-gray-900 mb-2">{{ appointment.title }}</h3>
                <p class="text-gray-600 mb-2">游戏：{{ appointment.game_name }}</p>
                <p class="text-sm text-gray-500">
                  预约时间：{{ formatDateTime(appointment.scheduled_time) }}
                </p>
              </div>
              <div class="flex items-center space-x-2">
                <span
                  :class="[
                    'px-3 py-1 rounded-full text-sm font-medium',
                    getStatusClass(appointment.status)
                  ]"
                >
                  {{ getStatusText(appointment.status) }}
                </span>
              </div>
            </div>

            <div class="flex justify-between items-center">
              <div class="text-sm text-gray-600">
                <span class="mr-4">当前人数：{{ appointment.current_players }}/{{ appointment.max_players }}</span>
                <span>参与者：{{ appointment.participants?.join(', ') || '暂无' }}</span>
              </div>
              
              <div class="flex space-x-2">
                <button
                  v-if="appointment.status === 'active'"
                  @click="closeAppointment(appointment.id)"
                  class="px-3 py-1 bg-red-500 text-white text-sm rounded hover:bg-red-600 transition-colors"
                >
                  关闭预约
                </button>
                <button
                  @click="editAppointment(appointment)"
                  class="px-3 py-1 bg-blue-500 text-white text-sm rounded hover:bg-blue-600 transition-colors"
                >
                  编辑
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 申请审核 -->
      <div v-if="activeTab === 'applications'" class="space-y-4">
        <div v-if="loading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <div v-else-if="applications.length === 0" class="text-center py-12">
          <div class="text-gray-400 text-6xl mb-4">📋</div>
          <h3 class="text-lg font-medium text-gray-900 mb-2">暂无申请</h3>
          <p class="text-gray-500">您的预约还没有收到申请</p>
        </div>

        <div v-else class="grid gap-4">
          <div
            v-for="application in applications"
            :key="application.id"
            class="glass rounded-lg p-6"
          >
            <div class="flex justify-between items-start mb-4">
              <div>
                <h4 class="text-lg font-semibold text-gray-900 mb-2">
                  {{ application.appointment_title }}
                </h4>
                <p class="text-gray-600 mb-2">游戏：{{ application.appointment_game_name }}</p>
                <p class="text-sm text-gray-500 mb-2">
                  申请人：{{ application.applicant_nickname || application.applicant_username }}
                </p>
                <p class="text-sm text-gray-500">
                  申请时间：{{ formatDateTime(application.applied_at) }}
                </p>
              </div>
              <span
                :class="[
                  'px-3 py-1 rounded-full text-sm font-medium',
                  getApplicationStatusClass(application.status)
                ]"
              >
                {{ getApplicationStatusText(application.status) }}
              </span>
            </div>

            <div v-if="application.reason" class="mb-4">
              <p class="text-sm text-gray-600 mb-1">申请理由：</p>
              <p class="text-gray-800 bg-gray-50 p-3 rounded">{{ application.reason }}</p>
            </div>

            <div v-if="application.status === 'pending'" class="flex space-x-2">
              <button
                @click="processApplication(application.id, 'approved')"
                class="px-4 py-2 bg-green-500 text-white text-sm rounded hover:bg-green-600 transition-colors"
              >
                通过
              </button>
              <button
                @click="processApplication(application.id, 'rejected')"
                class="px-4 py-2 bg-red-500 text-white text-sm rounded hover:bg-red-600 transition-colors"
              >
                拒绝
              </button>
            </div>

            <div v-if="application.admin_notes && application.status !== 'pending'" class="mt-4">
              <p class="text-sm text-gray-600 mb-1">处理备注：</p>
              <p class="text-gray-800 bg-gray-50 p-3 rounded text-sm">{{ application.admin_notes }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { appointmentAPI, applicationAPI } from '@/services/api'

const router = useRouter()
const activeTab = ref('appointments')
const loading = ref(false)
const appointments = ref([])
const applications = ref([])
const pendingCount = ref(0)

// 获取我创建的预约
const fetchMyAppointments = async () => {
  try {
    loading.value = true
    const response = await appointmentAPI.getMyAppointments()
    if (response.success !== false) {
      appointments.value = response.data || response
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取收到的申请
const fetchReceivedApplications = async () => {
  try {
    loading.value = true
    const response = await applicationAPI.getReceivedApplications()
    if (response.success !== false) {
      applications.value = response.data || response
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取待处理申请数量
const fetchPendingCount = async () => {
  try {
    const response = await applicationAPI.getPendingCount()
    if (response.success !== false) {
      pendingCount.value = response.data?.count || response.count || 0
    }
  } catch (error) {
    console.error('获取待处理申请数量失败:', error)
  }
}

// 关闭预约
const closeAppointment = async (appointmentId) => {
  if (!confirm('确定要关闭这个预约吗？关闭后将无法恢复。')) {
    return
  }

  try {
    const response = await appointmentAPI.closeAppointment(appointmentId)
    if (response.success !== false) {
      alert('预约已关闭')
      await fetchMyAppointments()
    }
  } catch (error) {
    console.error('关闭预约失败:', error)
    alert('关闭预约失败')
  }
}

// 处理申请
const processApplication = async (applicationId, status) => {
  const action = status === 'approved' ? '通过' : '拒绝'
  const adminNotes = prompt(`请输入${action}理由（可选）:`)
  
  if (adminNotes === null) return // 用户取消

  try {
    const response = await applicationAPI.processApplication(applicationId, {
      status,
      admin_notes: adminNotes || undefined
    })
    
    if (response.success !== false) {
      alert(`申请已${action}`)
      await fetchReceivedApplications()
      await fetchPendingCount()
    }
  } catch (error) {
    console.error('处理申请失败:', error)
    alert('处理申请失败')
  }
}

// 编辑预约
const editAppointment = (appointment) => {
  // 这里可以导航到编辑页面或打开编辑模态框
  console.log('编辑预约:', appointment)
  // router.push(`/appointments/${appointment.id}/edit`)
}

// 状态样式
const getStatusClass = (status) => {
  const classes = {
    active: 'bg-green-100 text-green-800',
    full: 'bg-yellow-100 text-yellow-800',
    cancelled: 'bg-red-100 text-red-800',
    completed: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getStatusText = (status) => {
  const texts = {
    active: '进行中',
    full: '已满员',
    cancelled: '已取消',
    completed: '已完成'
  }
  return texts[status] || status
}

const getApplicationStatusClass = (status) => {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800',
    approved: 'bg-green-100 text-green-800',
    rejected: 'bg-red-100 text-red-800',
    cancelled: 'bg-gray-100 text-gray-800'
  }
  return classes[status] || 'bg-gray-100 text-gray-800'
}

const getApplicationStatusText = (status) => {
  const texts = {
    pending: '待处理',
    approved: '已通过',
    rejected: '已拒绝',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 切换标签页时重新加载数据
const handleTabChange = () => {
  if (activeTab.value === 'appointments') {
    fetchMyAppointments()
  } else if (activeTab.value === 'applications') {
    fetchReceivedApplications()
  }
}

// 监听标签页变化
watch(() => activeTab.value, handleTabChange)

onMounted(async () => {
  await fetchMyAppointments()
  await fetchPendingCount()
})
</script>